package com.spooky.sync.net;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class NotePullService extends Service {
	private static final String TAG = "NotePullService";
	private PullServiceLife mPullServiceLife;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		// only once during lifetime
		if (mPullServiceLife == null || mPullServiceLife.isInterrupted()) {
			mPullServiceLife = new PullServiceLife();
		}
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) { //
		super.onStartCommand(intent, flags, startId);
		Log.d(TAG, "onStarted");
		// run when intent startService is Called
		if (!mPullServiceLife.isAlive()) {
			mPullServiceLife.start();
		}
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroyed");
		// Cleanup for onCreate
		mPullServiceLife.interrupt();
		mPullServiceLife = null;
	}

	private class PullServiceLife extends Thread {
		private static final int SLEEP_TIME = 60000;

		@Override
		public void run() {
			while (isInterrupted()) {
				Log.d(TAG, "Service");
				sleepTime();
			}
		}

		private void sleepTime() {
			if (!isInterrupted()) {
				try {
					Thread.sleep(SLEEP_TIME);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
